function setLocation(href){
    location.href = href;
}

function confirmDelete(href){
    if(confirm(Language.messages.confirmDelete)){
        location.href = href;
    }
}

String.prototype.trim = function(){
    return $.trim(this);
};

String.prototype.format = function(args){
    var str = this;
    var arr = str.match(/\{(\w+)\}/gi);
    for(var i = 0; i < arr.length; i++){
        var l = arr[i].length;
        str = str.replace(arr[i], args[arr[i].substring(1, l - 1)]);
    }
    return str;
};

String.prototype.pad = function(len, flag, type){
    var str = this;
    if(str.length < len){
        while(str.length < len){
            switch(type){
                case 'l':
                    str = flag + str;
                    break;
                case 'r':
                    str = str + flag;
                    break;
                default:
                    str = str + flag;
                    break;
            }
        }
    }
    return str;
};

jQuery.validator.addMethod('character', function(value){
    return /^\w+$/.test(value);
});

jQuery.validator.addMethod('rangeLength', function(value, element, params){
    return value.length >= params[0] && value.length <= params[1];
});

var Soul = {
    extend: function(bc, sc, o) {
        var f = function() {};
        f.prototype = sc.prototype;
        bc.prototype = new f();
        bc.prototype.constructor = bc;
        bc.superclass = sc.prototype;
        for (var m in o){
            bc.prototype[m] = o[m];
        }
    },

    setScope: function(callback, scope) {
        return function() {
            return callback.apply(scope, arguments);
        };
    },

    namespace: function() {
        var ns, d;
        for (var i = 0; i < arguments.length; i++) {
            ns = window;
            d = arguments[i].split(".");
            for (var j in d){
                ns = ns[d[j]] = ns[d[j]] ? ns[d[j]] : {};
            }
        }
    },

    isObject: function(obj) {
        return (obj && obj.constructor && obj.constructor == Object.prototype.constructor && !obj.nodeName)
        ? true : false;
    },

    globals:{
        forms:[],
        grids:[]
    },

    copyright: 'Keep Doing Studio'
};

Soul.Base = function() {
    if (Soul.isObject(arguments[0])) {
        var config = arguments[0];
        Soul.Base.superclass.init.call(this);
        this.initialize(config);
    } else {
        arguments.length > 0?
        Soul.Base.superclass.init.apply(this, arguments):
        Soul.Base.superclass.init.call(this);
    }
};

Soul.extend(Soul.Base, jQuery, {
    initialize: function(config) { }
});

Soul.Ajax = {};
Soul.Ajax.processResult = function(data, textStatus, request, setting){
    setting.resultHandler(data);
    return true;
};

Soul.Ajax.processError = function(request, textStauts){
    alert(request.statusText);
};

Soul.Ajax.load = function(setting){
    var config = jQuery.extend({}, {
        data:{},
        dataType:'text',
        method:'GET',
        cache: false
    }, setting);
    if(!config.resultHandler){
        config.resultHandler = function(data){
            config.success(data);
        };
    }

    jQuery.ajax({
        url:config.url,
        data:config.data,
        dataType:config.dataType,
        method:config.method,
        success:function(data, textStatus, request){
            Soul.Ajax.processResult(data, textStatus, request, setting);
        },
        error:function(request, textStatus, errorThrown){
            Soul.Ajax.processError(request, textStauts, errorThrown);
        }
    });
};

Soul.Ajax.loadJson = function(setting){
    setting.dataType = 'text';
    setting.resultHandler = function(data){
        var json = eval('(' + data + ')');
        setting.success(json);
    };
    Soul.Ajax.load(setting);
};

Soul.Ajax.loadHtml = function(setting){
    setting.dataType = 'html';
    setting.resultHandler = function(data){
        setting.success(data);
    };
    Soul.Ajax.load(setting);
};

Soul.UI = {};
Soul.UI.getForm = function(formId){
    return Soul.globals.forms[formId];
};

Soul.UI.getGrid = function(gridId){
    return Soul.globals.grids[gridId];
};

Soul.UI.Form = function(){
    this.form = null;
    this.validator = null;
    Soul.UI.Form.superclass.constructor.apply(this, arguments);
};

Soul.extend(Soul.UI.Form, Soul.Base, {
    initialize:function(setting){
        Soul.UI.Form.superclass.initialize.apply(this, arguments);
        this.setting = this.extend({}, {
            validate:true,
            ajax:false
        }, setting);
        this.form = jQuery(setting.form);
        this.form.bind('submit', Soul.setScope(this.submit, this));
    },

    setAction:function(url){
        this.form.attr('action', url);
        return this;
    },

    setHidden:function(name, value){
        this.form.find("input[name='" + name + "']").remove();
        if($.isArray(value)){
            for(var i = 0; i < value.length; i++){
                this.form.append('<input type="hidden" name="' + name + '" value="' + value[i] + '"/>');
            }
        }else{
            this.form.append('<input type="hidden" name="' + name + '" value="' + value + '"/>');
        }
        return this;
    },

    clearBackgroundText:function(){
        this.form.find(':text[backgroundText]').each(function(){
            $this = jQuery(this);
            if($this.val() == $this.attr('backgroundText')){
                $this.val('');
            }
        });
    },

    submit:function(){
        if(this.setting.validate){
            jQuery.metadata.setType('attr', 'validate');
//            this.clearBackgroundText();
            if(this.beforeValidate){
                this.beforeValidate(this);
            }
            if(!this.form.validate({onkeyup:false}).form()){
                if(this.validateFail){
                    this.validateFail(this);
                }
                return false;
            }
        }

        if(this.beforeSubmit){
            if(!this.beforeSubmit(this)){
                return false;
            }
        }
        
        if(this.setting.ajax){
            this.form.ajaxSubmit();
            return false;
        }
        this.setting.form.submit();
        return true;
    }
});

Soul.UI.Grid = function(){
    this.grid = null;
    this.setting = null;
    this.head = null;
    this.body = null;
    this.footer = null;
    this.rows = null;
    Soul.UI.Grid.superclass.constructor.apply(this, arguments);
};

Soul.extend(Soul.UI.Grid, Soul.Base, {
    initialize: function(setting){
        Soul.UI.Grid.superclass.initialize.apply(this, arguments);
        this.setting = this.extend({},{
            rowCheckBox:'.row-check input',
            rowHoverStyle:'hover',
            rowSelectedStyle:'selected',
            rowAllCheck:'.row-all-check'
        },
        setting);
        this.grid = jQuery(this.setting.grid);
        this.head = jQuery(this.grid.find('thead')[0]);
        this.body = jQuery(this.grid.find('tbody')[0]);
        this.footer = jQuery(this.grid.find('tfooter')[0]);
        this.rows = this.body.children('tr');

        this.rows.bind('mouseenter', Soul.setScope(this.onRowMouseEnter, this))
        .bind('mouseleave', Soul.setScope(this.onRowMouseLevel, this));
        jQuery(this.setting.rowCheckBox).bind('click', Soul.setScope(this.onRowCheckBoxClick, this));
        jQuery(this.setting.rowAllCheck).bind('click', Soul.setScope(this.onRowAllCheck, this));
    },

    onRowMouseEnter:function(event){
        jQuery(event.currentTarget).addClass(this.setting.rowHoverStyle);
    },

    onRowMouseLevel:function(event){
        jQuery(event.currentTarget).removeClass(this.setting.rowHoverStyle);
    },

    onRowCheckBoxClick:function(event){
        var $this = jQuery(event.currentTarget);
        if($this.attr('checked')){
        	$this.parent().parent().addClass(this.setting.rowSelectedStyle)
        }else{
        	jQuery(this.setting.rowAllCheck).removeAttr('checked');
        	$this.parent().parent().removeClass(this.setting.rowSelectedStyle);
        }
        
    },
    onRowAllCheck:function(event){
    	var $this = jQuery(event.currentTarget);
		if($this.attr('checked')){
	        jQuery(this.setting.rowCheckBox).attr('checked', 'checked');
	        this.rows.addClass(this.setting.rowSelectedStyle);
		}else{
	        jQuery(this.setting.rowCheckBox).removeAttr('checked');
	        this.rows.removeClass(this.setting.rowSelectedStyle);       		
		}
    },
    hasSelectedRow:function(){
        return jQuery(this.setting.rowCheckBox + ':checked').length > 0;
    }
});

jQuery(function(){
//    jQuery(':text[backgroundText]').each(function(){
//        $this = jQuery(this);
//        if(jQuery.trim($this.val()).length == 0){
//            $this.val($this.attr('backgroundText')).addClass('text-backgroundtext');
//        }
//        $this.bind('focus.backgroundText', function(){
//            $this = jQuery(this).addClass('text-hover');
//            if($this.val() == $this.attr('backgroundText')){
//                $this.val('');
//            }
//        }).bind('blur.backgroundText', function(){
//            $this = jQuery(this).removeClass('text-hover');
//            if(jQuery.trim($this.val()).length == 0){
//                $this.val($this.attr('backgroundText')).addClass('text-backgroundtext');
//            }else{
//                $this.removeClass('text-backgroundtext');
//            }
//        });
//    });

    jQuery('form').each(function(){
        Soul.globals.forms[jQuery(this).attr('id')] = new Soul.UI.Form({
            form:this
        });
    });
    jQuery('table.grid').each(function(){
        Soul.globals.grids[jQuery(this).attr('id')] = new Soul.UI.Grid({
            grid:this
        });
    });
    jQuery('input.datetime').each(function(){
        $(this).datepicker();
    });
});

function submitForm(formId, action){
    if(action){
    	Soul.UI.getForm(formId).setAction(action);
    }
    Soul.UI.getForm(formId).submit();
}

function deleteGridChecked(gridId, url){
    var grid = Soul.UI.getGrid(gridId);
    if(grid.hasSelectedRow()){
        if(confirm(Language.messages.confirmDelete)){
            var formId = $($('#' + gridId).parents('form')[0]).attr('id');
            Soul.UI.getForm(formId).setAction(url).submit();
        }
    }else{
        alert(Language.messages.selectGridItem);
    }
}

function submitGridChecked(gridId, url){
    var grid = Soul.UI.getGrid(gridId);
    if(grid.hasSelectedRow()){
        var formId = $($('#' + gridId).parents('form')[0]).attr('id');
        Soul.UI.getForm(formId).setAction(url).submit();
    }else{
        alert(Language.messages.selectGridItem);
    }
}